package myservice.android.activities;

import java.util.ArrayList;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.utilities.CheckBoxMonitor;
import myservice.android.utilities.EditTextMonitor;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CallActivity extends BaseSaveableActivity {
	
	private Button previousCallButton, nextCallButton, saveButton, deleteButton;
	private TextView personName, dateLabel, dateText, territoryText, houseText, apartmentHouseText, apartmentText, streetText, staircaseText;
	private EditText commentsText;
	private CheckBox bibleStudyConductedCheckbox;
	private ImageView personIcon, territoryIcon, streetIcon, apartmentHouseIcon, houseIcon, staircaseIcon, apartmentIcon;
	private RelativeLayout streetSection, apartmentHouseSection, staircaseSection, apartmentSection, houseSection;
	
	private ArrayList<Integer> callList = null;
	
	private int date, month, year;
	
	private long callId, personId, streetId, houseId, apartmentHouseId, apartmentId, territoryId, staircaseId;
	private long territoryElementId; // Territory element associated with this call	
	
	@Override
	protected void initializeLayoutIdAndTitle() {
		layoutId = R.layout.call;
		activityTitle = Global.res.getString(R.string.title_call);		
	}		
	
	@Override
	protected void retrieveViews() {
        previousCallButton = (Button) findViewById(R.id.previousButton);
        nextCallButton = (Button) findViewById(R.id.nextButton);     
        saveButton = (Button) findViewById(R.id.saveButton); 
        deleteButton = (Button) findViewById(R.id.deleteButton);  
        personIcon = (ImageView) findViewById(R.id.personIcon);
        personName = (TextView) findViewById(R.id.interestedName);
        dateLabel = (TextView) findViewById(R.id.dateLabel);
        dateText = (TextView) findViewById(R.id.dateText);
        territoryIcon = (ImageView) findViewById(R.id.territoryIcon);
        streetIcon = (ImageView) findViewById(R.id.streetIcon);
        apartmentHouseIcon = (ImageView) findViewById(R.id.apartmentHouseIcon);
        staircaseIcon = (ImageView) findViewById(R.id.staircaseIcon);
        apartmentIcon = (ImageView) findViewById(R.id.apartmentIcon);
        houseIcon = (ImageView) findViewById(R.id.houseIcon);
        territoryText = (TextView) findViewById(R.id.territoryName);
        houseText = (TextView) findViewById(R.id.houseName);
        apartmentText = (TextView) findViewById(R.id.apartmentName);
        streetText = (TextView) findViewById(R.id.streetName);
        staircaseText = (TextView) findViewById(R.id.staircaseName);        
        apartmentHouseText = (TextView) findViewById(R.id.apartmentHouseName);
        commentsText = (EditText) findViewById(R.id.commentsText);
        bibleStudyConductedCheckbox = (CheckBox) findViewById(R.id.bibleStudyConductedCheckbox);       
        apartmentHouseSection = (RelativeLayout) findViewById(R.id.apartmentHouseSection);
        apartmentSection = (RelativeLayout) findViewById(R.id.apartmentSection);
        houseSection = (RelativeLayout) findViewById(R.id.houseSection);        
        streetSection = (RelativeLayout) findViewById(R.id.streetSection);
        staircaseSection = (RelativeLayout) findViewById(R.id.staircaseSection); 
	}
	
	@Override
	protected void loadActivityParameters() {
		callId = activityParameters.getLong("call_id");
	}
	
	@Override
	protected void assignListeners() {
		
		commentsText.addTextChangedListener(new EditTextMonitor(this));
		
		bibleStudyConductedCheckbox.setOnCheckedChangeListener(new CheckBoxMonitor(this));
		
        previousCallButton.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View button) {
				Global.displayToast(CallActivity.this, Global.res.getString(R.string.tip_previous_call));
				return true;
			}        	
        });       
        
        saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				save();
				finish();
			}
        });
        
        deleteButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(CallActivity.this);
				alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
				alertDialogBuilder
					.setMessage(Global.res.getText(R.string.message_delete_call_confirmation))
					.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id) {
							Database.deleteCall(callId);
							finish();
						}
					  })
					.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
		 
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();				
			}        	
        });        
        
        nextCallButton.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View button) {
				Global.displayToast(CallActivity.this, Global.res.getString(R.string.tip_next_call));
				return true;
			}        	
        });                 
        
        OnClickListener clickPerson = new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickInterested();
			}    		
    	};    	  	
    	personName.setOnClickListener(clickPerson);    	
    	personIcon.setOnClickListener(clickPerson);  	
    	
    	OnLongClickListener longClickPerson = new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				if (personId==0)
					return false;
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(CallActivity.this);
				alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
				alertDialogBuilder
					.setMessage(Global.res.getText(R.string.message_unlink_person))
					.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id) {
							Database.execSQL("UPDATE calls SET personid=0, timestamp="+Global.getTimeStamp()+" WHERE callid="+callId);
							updateUi();
						}
					  })
					.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
		 
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
				return true;
			}    		
    	};    	
    	personName.setOnLongClickListener(longClickPerson);
    	personIcon.setOnLongClickListener(longClickPerson);
    	
    	territoryText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(territoryId);
			}    		
    	});  
    	territoryIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(territoryId);
			}    		
    	});      	
    	
    	streetText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(streetId);
			}    		
    	}); 
    	streetIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(streetId);
			}    		
    	});  
    	
    	houseText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(houseId);
			}    		
    	});
    	houseIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(houseId);
			}    		
    	});  
    	
    	apartmentHouseText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(apartmentHouseId);
			}    		
    	});    
    	apartmentHouseIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(apartmentHouseId);
			}    		
    	});  
    	
    	staircaseText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(staircaseId);
			}    		
    	});   
    	staircaseIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(staircaseId);
			}    		
    	});  
    	
    	apartmentText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(apartmentId);
			}    		
    	}); 
    	apartmentIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				clickTerritoryElement(apartmentId);
			}    		
    	});  
    	
    	OnLongClickListener longClickDate = new OnLongClickListener() {
			@Override
			public boolean onLongClick(View arg0) {
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(CallActivity.this);
				alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
				alertDialogBuilder
					.setMessage(Global.res.getText(R.string.message_change_date))
					.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id) {
							Intent i = new Intent(getApplicationContext(), PickDateActivity.class);			
							startActivity(i);			
						}
					  })
					.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});		 
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();							
				return true;
			}    		
    	};     	
    	dateText.setOnLongClickListener(longClickDate);
    	dateLabel.setOnLongClickListener(longClickDate);    	
    	
    	OnClickListener clickDate = new OnClickListener() {
			@Override
			public void onClick(View button) {
				save();
				Intent i = new Intent(getApplicationContext(),MinistryDetailsActivity.class);
			    i.putExtra("date",date);
			    i.putExtra("month",month);
			    i.putExtra("year",year);					    
			    startActivity(i);	
			}    		
    	};
    	dateText.setOnClickListener(clickDate);  
    	dateLabel.setOnClickListener(clickDate); 
    	
    	previousCallButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {				
				moveCall(false);									
			}			
    	});    
    	
    	nextCallButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {				
				moveCall(true);									
			}			
    	});    
    	
    	OnLongClickListener unlinkTerritory = new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
	    		if (territoryElementId==0)
	    			return false;
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(CallActivity.this);
				alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
				alertDialogBuilder
					.setMessage(Global.res.getText(R.string.message_unlink_territory))
					.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id) {
							Database.execSQL("UPDATE calls SET territoryid=0, timestamp="+Global.getTimeStamp()+" WHERE callid="+callId);
							updateUi();
						}
					  })
					.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
		 
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
				return true;
			}
    	};    	
    	territoryText.setOnLongClickListener(unlinkTerritory);
    	streetText.setOnLongClickListener(unlinkTerritory);
    	houseText.setOnLongClickListener(unlinkTerritory);
    	apartmentHouseText.setOnLongClickListener(unlinkTerritory);
    	staircaseText.setOnLongClickListener(unlinkTerritory);
    	apartmentText.setOnLongClickListener(unlinkTerritory);
    	territoryIcon.setOnLongClickListener(unlinkTerritory);
    	streetIcon.setOnLongClickListener(unlinkTerritory);
    	houseIcon.setOnLongClickListener(unlinkTerritory);
    	apartmentHouseIcon.setOnLongClickListener(unlinkTerritory);
    	apartmentIcon.setOnLongClickListener(unlinkTerritory);
    	staircaseIcon.setOnLongClickListener(unlinkTerritory);
	}	   		
    
	@Override
    protected void updateUi() {   
		
    	territoryElementId = 0;
		
		Cursor cursor;		    				    
    	
    	if (Global.selectedId!=0) { // Something somewhere was picked from a list
    		
    		if (Global.selectedType==0) { // interested person was picked
    			personId=Global.selectedId;
    			Database.execSQL("UPDATE calls SET personid="+personId+", timestamp="+Global.getTimeStamp()+" WHERE callid="+callId); 
    			
    			int ter=0;
    			cursor = Database.select("SELECT territoryid FROM calls WHERE callid="+callId);
    			cursor.moveToNext();
    			ter=cursor.getInt(cursor.getColumnIndex("territoryid"));
    			cursor.close();
    			
    			if (ter!=0) { // Ask the user to assign the selected person to all recorded calls to this apartment/house if other calls to this apartment/house exist
    				
    				// Check if other unlinked calls to this apartment/house exist
    				cursor = Database.select("SELECT COUNT(*) AS c FROM calls WHERE personid=0 AND territoryid="+ter+" AND callid<>"+callId+" AND timestamp<>"+Global.TIMESTAMP_DELETED);
    				cursor.moveToNext();
    				int callCount = cursor.getInt(cursor.getColumnIndex("c"));
    				cursor.close();
    				
    				if (callCount>0) { // At least one unlinked call exists
    				
	    				final int tid = ter;
	    				
	    				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(CallActivity.this);
	    				alertDialogBuilder.setTitle(Global.res.getText(R.string.title_question));				
	    				alertDialogBuilder
							.setMessage(Global.res.getText(R.string.message_link_person))
							.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
										Database.execSQL("UPDATE calls SET personid="+personId+", timestamp="+Global.getTimeStamp()+" WHERE territoryid="+tid+" AND timestamp<>"+Global.TIMESTAMP_DELETED);
								}
							})
							.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});    			
			 
	    				AlertDialog alertDialog = alertDialogBuilder.create();
	    				alertDialog.show();
    				}
    			}
    			
    		} else if (Global.selectedType==1) { // house or apartment was picked
    			territoryElementId=Global.selectedId;
    			Database.execSQL("UPDATE calls SET territoryid="+territoryElementId+", timestamp="+Global.getTimeStamp()+" WHERE callid="+callId);    			
    		} else if (Global.selectedType==2) { // date was picked    			
    			date = Global.selectedDate;
    			month = Global.selectedMonth;
    			year = Global.selectedYear;
    			Database.execSQL("UPDATE calls SET date="+date+", month="+month+", year="+year+" WHERE callid="+callId);
    		}
    		
    		Global.selectedId=0;
    			
    	}   
    	
		cursor = Database.select("SELECT * FROM calls WHERE callid="+callId+" AND timestamp<>"+Global.TIMESTAMP_DELETED);
		try {
			cursor.moveToNext();
			date=cursor.getInt(cursor.getColumnIndex("date"));
			month=cursor.getInt(cursor.getColumnIndex("month"));
			year=cursor.getInt(cursor.getColumnIndex("year"));
			personId=cursor.getInt(cursor.getColumnIndex("personid"));
			territoryElementId=cursor.getInt(cursor.getColumnIndex("territoryid"));
			commentsText.setText(cursor.getString(cursor.getColumnIndex("comments")));
			if (cursor.getInt(cursor.getColumnIndex("biblestudy"))==0)
				bibleStudyConductedCheckbox.setChecked(false);
			else
				bibleStudyConductedCheckbox.setChecked(true);		
		} catch (Exception e) {
			finish();
		} finally {
			cursor.close();
		} 		    	
		
    	dateText.setText(Global.getFormattedDate(year, month, date));		
    	
    	// Get the person info
		if (personId!=0) {
			cursor = Database.select("SELECT name,status FROM persons WHERE personid="+personId);    	
			if (cursor.moveToNext()==true) {
				personName.setText(cursor.getString(cursor.getColumnIndex("name")));
				int status = cursor.getInt(cursor.getColumnIndex("status"));
				if (status==0)
        			personIcon.setImageDrawable(Global.res.getDrawable(R.drawable.person_inactive));
        		else if (status==1)
        			personIcon.setImageDrawable(Global.res.getDrawable(R.drawable.person_interested));
        		else if (status==2)
        			personIcon.setImageDrawable(Global.res.getDrawable(R.drawable.person_magreader));
        		else if (status==3)
        			personIcon.setImageDrawable(Global.res.getDrawable(R.drawable.person_study));
			}
			cursor.close();
			bibleStudyConductedCheckbox.setVisibility(View.VISIBLE);
		} else {
			personIcon.setImageDrawable(Global.res.getDrawable(R.drawable.person_inactive));
			personName.setText(Global.res.getString(R.string.label_not_specified));
			bibleStudyConductedCheckbox.setVisibility(View.GONE);
		}
		
		// Get territory info
		streetSection.setVisibility(View.GONE);
		staircaseSection.setVisibility(View.GONE);		
		apartmentHouseSection.setVisibility(View.GONE);
		apartmentSection.setVisibility(View.GONE);
		houseSection.setVisibility(View.GONE);
		if (territoryElementId==0) {
			territoryText.setText(Global.res.getString(R.string.label_not_specified));
			territoryId=0;
		} else {				
			long tid = territoryElementId;
			while (tid!=0) {
				Cursor c = Database.select("SELECT type,parent,name FROM territories WHERE territoryid="+tid+" AND timestamp<>"+Global.TIMESTAMP_DELETED);
				c.moveToNext();
				int type = c.getInt(c.getColumnIndex("type"));
				int parent = c.getInt(c.getColumnIndex("parent"));
				String name = c.getString(c.getColumnIndex("name"));
				if (type==0) { // territory
					territoryId=tid;
					territoryText.setText(name);
				} else if (type==1) { // street
					streetId=tid;
					streetSection.setVisibility(View.VISIBLE);
					streetText.setText(name);
				} else if (type==2) { // house
					houseId=tid;
					houseSection.setVisibility(View.VISIBLE);
					houseText.setText(name);
				} else if (type==3) { // apartment house
					apartmentHouseId=tid;
					apartmentHouseSection.setVisibility(View.VISIBLE);
					apartmentHouseText.setText(name);					
				} else if (type==4) { // staircase
					staircaseId=tid;
					staircaseSection.setVisibility(View.VISIBLE);
					staircaseText.setText(name);
				} else if (type==5) { // apartment
					apartmentId=tid;
					apartmentSection.setVisibility(View.VISIBLE);
					apartmentText.setText(name);					
				}
				c.close();
				tid=parent;
			}
		}
    	
    }
    
	@Override
    protected void save() {
		
		activityContentModified = false;
    	
    	commentsText.clearFocus();
    	    
		int bs;
		if (bibleStudyConductedCheckbox.isChecked())
			bs=1;
		else
			bs=0;	
			
    	Database.execSQL("UPDATE calls SET date="+date+", month="+month+", year="+year+", timestamp="+Global.getTimeStamp()+
    			         ", comments='"+Global.fixText(commentsText.getText())+"', biblestudy="+bs+" WHERE callid="+callId);    	    	
    	
    }
    
    private void buildCallList() {
    	
		callList = new ArrayList<Integer>();
		
		Cursor cursor;
		
		if (personId!=0)
			cursor = Database.select("SELECT callid FROM calls WHERE personid="+personId+" AND timestamp<>"+Global.TIMESTAMP_DELETED+" ORDER BY year, month, date");
		else if (territoryElementId!=0)
			cursor = Database.select("SELECT callid FROM calls WHERE personid=0 AND territoryid="+territoryElementId+" AND timestamp<>"+Global.TIMESTAMP_DELETED+" ORDER BY year, month, date");
		else
			cursor = Database.select("SELECT callid FROM calls WHERE personid=0 AND territoryid=0 AND timestamp<>"+Global.TIMESTAMP_DELETED+" ORDER BY year, month, date");

    	while (cursor.moveToNext()) {
    		Integer rec = cursor.getInt(cursor.getColumnIndex("callid"));   		
    		callList.add(rec);
    	}	
    	cursor.close(); 
    	
    }
    
    /** Switches the call either to the previous one, or to the next one */
    private void moveCall(boolean forward) {
    	    	
   		buildCallList(); 
    	
    	if (callList==null)
    		return;
    	
    	if (callList.size()<2)
    		return;
    	
    	save();   	
    	
    	// Locate the current call in the list
    	int i=0;
    	while (callList.get(i)!=callId) {
    		i++;
    	}
    	
    	if (i==0 && forward==false)
    		return;
    	
    	if (i==callList.size()-1 && forward==true)
    		return;
    	
    	if (forward==true)
    		i++;
    	else
    		i--;
    	
    	callId=callList.get(i);   	    	
    	
    	updateUi();
    	
    	activityContentModified = false;
    	
    }   
    
    private void clickTerritoryElement(long tid) {  
    	
    	save();
    	
    	if (tid==0) {    	
    		Global.selectedId=0;
    		Intent i = new Intent(getApplicationContext(), TerritoryListActivity.class);
    		i.putExtra("mode",1); //Indicates that the user only wants to pick a house/apartment from the list, not modify buildings
    		startActivity(i);
    	} else {
    		Intent i = new Intent(getApplicationContext(),TerritoryElementActivity.class);
    		i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    		i.putExtra("territory_id",tid);
    		i.putExtra("mode", 0);
    		startActivity(i);	
    	}
    }    
    
    private void clickInterested() {
    	
    	save();
    	
    	if (personId!=0) {
    		Intent i = new Intent(getApplicationContext(),PersonActivity.class);
    		i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    		i.putExtra("person_id",personId);
    		startActivity(i);
    	} else {
			Global.selectedId=0;
			Intent i = new Intent(getApplicationContext(), PersonListActivity.class);
			i.putExtra("mode",1); //Indicates that the user only wants to pick a person from the list, not modify persons
			startActivity(i);    		
    	}
    }
}